/**
 * Copyright 2021 Hannes Dorfmann.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.hannesdorfmann.mosby3.sample.mvi.view.widge;

import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Image;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;

public class CirleProgressImg extends Image {

    private Context mComponentContext;
    private Context context;
    private AnimatorProperty mAnimator;
    TaskDispatcher dispatcher;

    public CirleProgressImg(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public CirleProgressImg(Context context, AttrSet attrSet) {
        super(context, attrSet);
        this.context = context;
        init();

    }

    public CirleProgressImg(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        this.context = context;
        init();
    }

    public void setmComponentContext(Context mComponentContext){
        this.mComponentContext = mComponentContext;
    }

    private void init(){
        initAnim();
    }

    private void initAnim(){
        mAnimator = this.createAnimatorProperty();
        mAnimator.rotate(360).setDuration(700).setDelay(100).setLoopedCount(AnimatorProperty.INFINITE);
    }


    public void firtLoadStart(){

        dispatcher =  context.getMainTaskDispatcher();
        dispatcher.delayDispatch(new Runnable() {
            @Override
            public void run() {
                startAnime();
            }
        }, 50);
    }

    public void startAnime(){
        if(mAnimator != null){
            mAnimator.start();
        }
    }

    public void start(){
        firtLoadStart();
    }

    public void stop(){
        if(mAnimator != null){
            mAnimator.stop();
        }
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);

        if(visibility == VISIBLE){
            if(mAnimator != null ){
                if(mAnimator.isRunning()){
                    mAnimator.stop();
                }
                firtLoadStart();
            }

        }else{
            if(mAnimator != null && mAnimator.isRunning()){
                stop();
            }
        }

    }
}
